package com.nulp.psycho.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.nulp.psycho.db.model.User;
import com.nulp.psycho.db.service.UserService;



public class CookiesListener implements ServletRequestListener {


    public CookiesListener() {     
    }

    public void requestDestroyed(ServletRequestEvent arg0)  { 
    }

    public void requestInitialized(ServletRequestEvent event)  { 
    	HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
    	User user = (User) request.getSession(true).getAttribute("user");
    	if ((user == null)&&(request.getCookies()!=null)) {
			Cookie[] cookies = request.getCookies();
			Cookie cookie = getCookieForName(cookies, "login");
			if ((cookie != null)&&(cookie.getValue()!=null)) {			
				UserService userService =new UserService();
				user = userService.getUserByLogin(cookie.getValue());
				request.getSession(true).setAttribute("user", user);
			}
		}
    }

	private Cookie getCookieForName(Cookie[] cookies, String name) {
		for(int i=0;i<cookies.length;i++){
			if(cookies[i].getName().equals(name)){
				return cookies[i];
			}
		}
		return null;
	}
	
}
